<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="告警类型" prop="alarmType">
        <el-select
          v-model="queryParams.alarmType"
          placeholder="请选择告警类型"
          style="width: 240px"
          @change="handleAlarmTypeChange"
        >
          <el-option
            v-for="dict in dict.type.alarm_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="deviceNo">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备ID"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通道" prop="chanel">
        <el-input
          v-model="queryParams.chanel"
          placeholder="请输入通道"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="eventStatus">
        <el-select
          v-model="queryParams.eventStatus"
          placeholder="请选择状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.alarm_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 新增断纤位置区间查询 -->
      <template v-if="(queryParams.alarmType == '' || queryParams.alarmType==3)">
        <el-form-item label="米标范围">
          <el-input
            v-model="queryParams.minMeterMark"
            placeholder="最小米标"
            clearable
            style="width: 110px"
          />
          <span style="margin: 0 5px">-</span>
          <el-input
            v-model="queryParams.maxMeterMark"
            placeholder="最大米标"
            clearable
            style="width: 110px"
          />
        </el-form-item>
        <el-form-item label="单元" prop="unitName">
          <el-input
            v-model="queryParams.unitName"
            placeholder="请输入单元名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="电梯" prop="elevatorName">
          <el-input
            v-model="queryParams.elevatorName"
            placeholder="请输入电梯名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="楼层" prop="floorName">
          <el-input
            v-model="queryParams.floorName"
            placeholder="请输入楼层名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="位置编码" prop="lcCode">
          <el-input
            v-model="queryParams.lcCode"
            placeholder="请输入位置编码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </template>
      <el-form-item label="断纤位置范围" v-if="(queryParams.alarmType == '' || queryParams.alarmType==1)">
        <el-input
          v-model="queryParams.minFiberBreakPosition"
          placeholder="最小位置"
          clearable
          style="width: 110px"
        />
        <span style="margin: 0 5px">-</span>
        <el-input
          v-model="queryParams.maxFiberBreakPosition"
          placeholder="最大位置"
          clearable
          style="width: 110px"
        />
      </el-form-item>
      <el-form-item label="告警时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="楼栋" prop="buildingName">
        <el-input
          v-model="queryParams.buildingName"
          placeholder="请输入楼栋名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 新增批量处理按钮 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchHandle"
          v-hasPermi="['project:event:handle']"
        >批量处理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:event:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmEventList" @selection-change="handleSelectionChange">
      <!-- 已处理的事件不显示选择框 -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :selectable="selectable"
      />
      <el-table-column label="事件id" align="center" prop="id" width="70" />
      <el-table-column label="告警类型" align="center" prop="alarmType" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.alarm_type" :value="scope.row.alarmType"/>
        </template>
      </el-table-column>
      <el-table-column label="设备&通道" align="center" prop="deviceNo" width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceNo }}-{{ scope.row.chanel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="位置" align="center" prop="lcName" v-if="(queryParams.alarmType == '' || queryParams.alarmType==3)" width="280" />
      <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==3)" label="米标" align="center" prop="meterMark" width="70"/>
      <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==1)" label="断纤告警位置" align="center" prop="fiberBreakPosition" width="100"/>
      <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==2)" label="激光器温度" align="center" prop="laserTemperature" width="100"/>

      <el-table-column v-if="(queryParams.alarmType == '' || queryParams.alarmType==3)" label="温度范围" align="center" prop="maxTemperature" width="100">
        <template slot-scope="scope">
          {{scope.row.maxTemperature}}-{{ scope.row.minTemperature }}
        </template>
      </el-table-column>

      <!-- 在表格列定义中添加位置信息列 -->

      <el-table-column label="数量" align="center" prop="alarmCount" width="70">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="handleViewRecords(scope.row)"
          >{{ scope.row.alarmCount }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="eventStatus" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.alarm_state" :value="scope.row.eventStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="告警开始时间" align="center" prop="alarmStartTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.alarmStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="告警结束时间" align="center" prop="alarmEndTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.alarmEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="告警处理时间" align="center" prop="eventHandledTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.eventHandledTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 已处理的事件不显示处理按钮 -->
          <el-button
            v-if="scope.row.eventStatus !== 2"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleSingleHandle(scope.row)"
            v-hasPermi="['project:event:handle']"
          >处理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 处理对话框 -->
    <el-dialog :title="handleTitle" :visible.sync="handleOpen" width="500px" append-to-body>
      <el-form ref="handleForm" :model="handleForm" :rules="handleRules" label-width="80px">
        <el-form-item label="处理意见" prop="handledResult">
          <el-input
            v-model="handleForm.handledResult"
            type="textarea"
            placeholder="请输入处理意见"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHandleForm">确 定</el-button>
        <el-button @click="cancelHandle">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAlarmEvent, handleEvent, handleEventBatch } from "@/api/project/event"

export default {
  name: "Event",
  dicts: ['alarm_type', 'alarm_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 告警事件表格数据
      alarmEventList: [],
      // 日期范围
      dateRange: [],
      // 处理对话框相关
      handleOpen: false,
      handleTitle: "",
      handleForm: {
        handledResult: ""
      },
      handleRules: {
        handledResult: [
          {required: true, message: "处理意见不能为空", trigger: "blur"}
        ]
      },
      currentHandleIds: [], // 当前要处理的事件ID数组
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmType: '3',
        deviceNo: undefined,
        chanel: undefined,
        eventStatus: '0',
        minMeterMark: undefined,
        maxMeterMark: undefined,
        minFiberBreakPosition: undefined,
        maxFiberBreakPosition: undefined,
        // 新增位置查询字段
        buildingName: undefined,
        unitName: undefined,
        elevatorName: undefined,
        floorName: undefined,
        lcCode: undefined
      }
    }
  },
  created() {
    this.parseUrlParams()
    this.getList()
  },
  methods: {
    // 解析URL参数并设置查询条件
    parseUrlParams() {
      const urlParams = new URLSearchParams(window.location.search);

      // 设置告警类型
      if (urlParams.has('alarmType')) {
        this.queryParams.alarmType = urlParams.get('alarmType');
      }

      // 设置状态
      if (urlParams.has('eventStatus')) {
        this.queryParams.eventStatus = urlParams.get('eventStatus');
      }

      // 可以继续添加其他参数的解析
      if (urlParams.has('deviceNo')) {
        this.queryParams.deviceNo = urlParams.get('deviceNo');
      }
      if (urlParams.has('chanel')) {
        this.queryParams.chanel = urlParams.get('chanel');
      }

      // 新增位置参数解析
      if (urlParams.has('buildingName')) {
        this.queryParams.buildingName = urlParams.get('buildingName');
      }
      if (urlParams.has('unitName')) {
        this.queryParams.unitName = urlParams.get('unitName');
      }
      if (urlParams.has('elevatorName')) {
        this.queryParams.elevatorName = urlParams.get('elevatorName');
      }
      if (urlParams.has('floorName')) {
        this.queryParams.floorName = urlParams.get('floorName');
      }
      if (urlParams.has('lcCode')) {
        this.queryParams.lcCode = urlParams.get('lcCode');
      }

      console.log('URL参数解析结果:', this.queryParams);
    },
    // 判断行是否可选（已处理的事件不可选）
    selectable(row, index) {
      return row.eventStatus !== 2; // 2表示已处理状态
    },
    // 告警类型变更处理
    handleAlarmTypeChange() {
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },
    /** 查询告警事件列表 */
    getList() {
      this.loading = true
      listAlarmEvent(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.alarmEventList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      // 手动重置位置查询字段
      this.queryParams.buildingName = undefined
      this.queryParams.unitName = undefined
      this.queryParams.elevatorName = undefined
      this.queryParams.floorName = undefined
      this.queryParams.lcCode = undefined
      this.queryParams.alarmType = '3'
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 过滤掉已处理的事件
      const validSelection = selection.filter(item => item.eventStatus !== 2);
      this.ids = validSelection.map(item => item.id)
      this.single = validSelection.length != 1
      this.multiple = !validSelection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$router.push('/project/event/detail/' + row.id)
    },
    /** 查看告警记录操作 */
    handleViewRecords(row) {
      const queryParams = {
        alarmType: row.alarmType,
        deviceNo: row.deviceNo,
        chanel: row.chanel,
        status: row.status,
        minMeterMark: row.meterMark,
        maxMeterMark: row.meterMark,
        fiberBreakPosition: row.fiberBreakPosition
      }
      this.$router.push({
        path: '/project/record',
        query: queryParams
      })
    },
    /** 单个处理按钮操作 */
    handleSingleHandle(row) {
      this.currentHandleIds = [row.id];
      this.handleTitle = "处理事件 - " + row.id;
      this.handleForm.handledResult = "";
      this.handleOpen = true;
    },
    /** 批量处理按钮操作 */
    handleBatchHandle() {
      if (this.ids.length === 0) {
        this.$modal.msgWarning("请选择要处理的事件");
        return;
      }
      this.currentHandleIds = this.ids;
      this.handleTitle = "批量处理事件 (" + this.ids.length + "个)";
      this.handleForm.handledResult = "";
      this.handleOpen = true;
    },
    /** 提交处理表单 */
    submitHandleForm() {
      this.$refs["handleForm"].validate(valid => {
        if (valid) {
          const handledBy = this.$store.state.user.name;

          // 创建请求数据对象
          const requestData = {
            handledResult: this.handleForm.handledResult,
            handledBy: handledBy
          };

          if (this.currentHandleIds.length === 1) {
            // 单个处理
            requestData.eventId = this.currentHandleIds[0];
            this.handleSingleEvent(requestData);
          } else {
            // 批量处理
            requestData.eventIds = this.currentHandleIds;
            this.handleBatchEvent(requestData);
          }
        }
      });
    },
    /** 处理单个事件 */
    handleSingleEvent(data) {
      handleEvent(data).then(response => {
        this.$modal.msgSuccess("处理成功");
        this.handleOpen = false;
        this.resetHandleForm();
        this.getList();
      }).catch(error => {
        console.error('处理事件失败:', error);
        this.$modal.msgError("处理失败");
      });
    },

    /** 批量处理事件 */
    handleBatchEvent(data) {
      // 将eventIds中的数字转换为Long类型（字符串形式）
      const requestData = {
        eventIds: data.eventIds.map(id => id.toString()), // 转换为字符串
        handledResult: data.handledResult,
        handledBy: data.handledBy
      };

      handleEventBatch(requestData).then(response => {
        this.$modal.msgSuccess(response.msg || `成功处理 ${data.eventIds.length} 个事件`);
        this.handleOpen = false;
        this.resetHandleForm();
        this.getList();
      }).catch(error => {
        console.error('批量处理事件失败:', error);
        this.$modal.msgError("批量处理失败");
      });
    },
    /** 取消处理 */
    cancelHandle() {
      this.handleOpen = false;
      this.resetHandleForm();
    },
    /** 重置处理表单 */
    resetHandleForm() {
      this.handleForm = {
        handledResult: ""
      };
      this.currentHandleIds = [];
      this.resetForm("handleForm");
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/event/export', {
        ...this.queryParams
      }, `alarmEvent_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
